﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (Session["UserLogIn"] != null)
            Response.Redirect("Menu.aspx");
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Login1.CssClass = "";
    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if (CheckCredentials(Login1.UserName, Login1.Password))
        {
            Session["UserLogIn"] = Login1.UserName;

            //redirect back to calling page once user is authenticated
            Response.Redirect(Request.UrlReferrer.ToString());           
        }
        else
        {
            e.Authenticated = false;
        }
    }

    private bool CheckCredentials(string UserName, string Password)

    {
        bool authenticated = false;

        string strConnection = "Data Source=csd.columbusstate.edu;Initial Catalog=6118_fa12_TeamC;User ID=student;Password=cscpsc12";

        SqlConnection connection = new SqlConnection(strConnection);

        String query = "SELECT UNAME, PWD FROM CUSTOMER";

        SqlCommand command = new SqlCommand(query, connection);

        SqlDataReader reader;

        connection.Open();

        reader = command.ExecuteReader();

        while (reader.Read())
        {
            if ((UserName == reader["UNAME"].ToString()) && (Password == reader["PWD"].ToString()))
            {
                authenticated = true;

                reader.Close();

                return authenticated;
            }            
        }

        reader.Close();
        return authenticated;
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Register.aspx");
    }
}

